/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tmgt.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.hyperic.sigar.ProcState;
import org.hyperic.sigar.ProcUtil;
import org.hyperic.sigar.Sigar;
import tmgt.ProcessComparator;
import tmgt.Processinfo;

/**
 *
 * @author joel
 */
public class SigarHelper {

    public static List<Processinfo> retrieveProcesses()  {
        Sigar sigar = new Sigar();

        List<Processinfo> list = new ArrayList<Processinfo>();
        try {
            long[] pids = sigar.getProcList();

            for (int i = 0; i < pids.length; i++) {
                long pid = pids[i];
                ProcState state = sigar.getProcState(pid);

                String desc = ProcUtil.getDescription(sigar, pid);
                Processinfo pInfo = new Processinfo();
                pInfo.setProcessid(pid);
                pInfo.setDescription(desc);
                pInfo.setName(state.getName());
                list.add(pInfo);

            }
        } catch (Exception e) {
        }

        return list;

    }

    public static List<Processinfo> retrieveExistingProcesses() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("mydbPU");
        EntityManager entityManager = emf.createEntityManager();
        javax.persistence.Query  query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT p FROM Processinfo p"); // NOI18N
        return query.getResultList();
    }

    public static List retrieveNewProcesses() {
         Set s1 = new TreeSet(new ProcessComparator());
         Collection c1 = retrieveProcesses();
         s1.addAll(c1);
         Collection c2 = retrieveExistingProcesses();
         s1.removeAll(c2);
         return new ArrayList(s1);
    }

}
